package com.cskaoyan.javase.homework.senior._06reflect;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: songtao@cskaoyan.onaliyun.com
 **/

public class NetworkUtils {
    public static DatagramPacket getSendPacket(String msg, String ip, int port) throws UnknownHostException {
        byte[] bytes = msg.getBytes();
        InetAddress targetIp = InetAddress.getByName(ip);
        DatagramPacket sendPacket =
                new DatagramPacket(bytes, 0, bytes.length, targetIp, port);
        return sendPacket;
    }

    public static DatagramPacket getReceivePacket() {
        byte[] bytes = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);
        return receivePacket;
    }

    public static String parseMsg(DatagramPacket receivePacket) {
        byte[] data = receivePacket.getData();
        int offset = receivePacket.getOffset();
        int length = receivePacket.getLength();
        String s = new String(data, offset, length);
        return s;
    }
}
